package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MapperStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @ClassName: XMLMapperBuilder
 * @Description: mapper.xml解析创建类：用来创建MapperStatement
 * @Author: qiaojiacheng
 * @Date: 2021/7/22 2:49 下午
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream resourceAsStream) throws DocumentException, ClassNotFoundException {
        Document document = new SAXReader().read(resourceAsStream);

        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        List<Element> selectList = rootElement.selectNodes("//select");
        selectList.addAll(rootElement.selectNodes("//insert"));
        selectList.addAll(rootElement.selectNodes("//delete"));
        selectList.addAll(rootElement.selectNodes("//update"));
        for (Element element : selectList) {
            String id = element.attributeValue("id");
            String parameterType = element.attributeValue("parameterType");
            String resultType = element.attributeValue("resultType");
            String textTrim = element.getTextTrim();

            MapperStatement mapperStatement = new MapperStatement();
            mapperStatement.setId(id);
            if (parameterType != null) {
                Class<?> parameterTypeClass = getClassType(parameterType);
                mapperStatement.setParameterType(parameterTypeClass);
            }
            Class<?> resultTypeClass = getClassType(resultType);
            mapperStatement.setResultType(resultTypeClass);
            mapperStatement.setSql(textTrim);
            String statementId = namespace + "." + id;
            configuration.getMapperStatementMap().put(statementId, mapperStatement);
        }
    }

    private Class<?> getClassType(String resultType) throws ClassNotFoundException {
        Class<?> aClass = Class.forName(resultType);
        return aClass;
    }


}
